import os
import re

PACKET_DIC = {}
ID_DIC = {}
_id_index = 0
_id = 0

protoPath = os.path.join(os.path.dirname(__file__), "PBMessage.proto")
with open(protoPath, "r", encoding="utf-8") as f:
    all_lines = f.readlines()

    # 遍历每行并查找符合条件的消息类型
    for i, curr_line in enumerate(all_lines):
        # 如果当前行以'message'关键字开头，则说明找到了一个新的消息类型
        if curr_line.startswith('message'):
            try:
                # 获取该消息类型的名称
                message_name = curr_line.split() [ 1 ].strip('{')

                # 计算该消息类型的上下文
                prev_line = all_lines [ i - 1 ].strip() if i > 0 else None
                next_line = all_lines [ i + 2 ].strip() if i < len(all_lines) - 1 else None

                # 获取消息包id
                target_keyword = '//'
                match = re.search(rf'{target_keyword}\s*(\d+)\s*', prev_line)
                if match:
                    try:
                        num_str = match.group(1)
                        message_num = int(num_str)
                        # 不匹配直接不填入 否则后面的值会覆盖前面的值
                        PACKET_DIC [ int(message_num) ] = message_name.strip()
                        ID_DIC [ message_name.strip() ] = int(message_num)
                    except:
                        pass
                else:
                    pass
            except:
                pass


# print(PACKET_DIC)
def PACKET_DEFINE(idnumber):
    return PACKET_DIC [ idnumber ]


def ID_DEFINE(packetname):
    return ID_DIC [ packetname ]


def Info_ID():
    return max(PACKET_DIC.keys()),min(PACKET_DIC.keys())


def HAS_ID(idnumber):
    return idnumber in PACKET_DIC


if __name__ == "__main__":
    print(ID_DEFINE('AnotherUserInfoReq'))
    print(PACKET_DIC [ 80211 ])
    # print(Info_ID())

    